from config.Varconfig import testdataPath
from scripts import excel
from scripts.add_person import add_person
from until.generate_func import generate_func_express
from action.elementAction import *


def testAndContract():
    try:
        case_sheet = excel.get_sheet_by_name('loginandsendmail')

        case_nums = excel.get_row_nums(case_sheet)
        for i in range(2,case_nums+1):
            if excel.get_cell_values(i,7,case_sheet).lower() == 'y':
                case_name = excel.get_cell_values(i,2,case_sheet)
                driver_mod = excel.get_cell_values(i,4,case_sheet)
                step_sheet_name = excel.get_cell_values(i,6,case_sheet)
                # print(f'{case_name}-{driver_mod}-{step_sheet_name}')

                if driver_mod.lower() == 'data':
                    datasource_sheet_name = excel.get_cell_values(i,5,case_sheet)
                    datasource_sheet = excel.get_sheet_by_name(datasource_sheet_name)
                    step_sheet = excel.get_sheet_by_name(step_sheet_name)
                    result = add_person(datasource_sheet,step_sheet)

                    if result == 'pass':
                        print(f'case {case_name} success')
                        excel.write_value(i,8,'pass',testdataPath,case_sheet)
                    else:
                        print(f'case {case_name} fail')
                        excel.write_value(i, 8, 'fail', testdataPath, case_sheet)

                elif driver_mod.lower() == 'keyword':
                    step_sheet = excel.get_sheet_by_name(step_sheet_name)
                    step_nums = excel.get_row_nums(step_sheet)

                    success_record = 0
                    for j in range(2,step_nums+1):
                        step_desc = excel.get_cell_values(j,2,step_sheet)
                        key_word = excel.get_cell_values(j,3,step_sheet)
                        location_type = excel.get_cell_values(j,4,step_sheet)
                        location_express = excel.get_cell_values(j,5,step_sheet)
                        oprecate_value  = excel.get_cell_values(j,6,step_sheet)

                        method_express = generate_func_express(key_word,location_type,location_express,oprecate_value)

                        try:
                            print(f"start action {step_desc}")
                            eval(method_express)
                        except Exception as e:
                            print(f'action {step_desc} {e}')
                            excel.write_value(i,8,'fail',testdataPath,case_sheet)
                        else:
                            print(f'{step_desc} action success')
                            success_record += 1

                    if success_record+1 == step_nums:
                        excel.write_value(i,8,'pass',testdataPath,case_sheet)

    except Exception as e:
        print(e)
if __name__ == '__main__':
    testAndContract()